package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.mall.lib.domain.MallOrder;
import com.rockcent.mall.lib.domain.MessageReplyRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by caihongli on 2017/6/6.
 */
@Repository
public class MallWechatMessageReplyRuleRepositoryImpl implements MallWechatMessageReplyRuleRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(MallWechatMessageReplyRuleRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<MessageReplyRule> findRulesByKeywordAndMallId(String keyword, Long mallId) {
        SQLListDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from message_reply_rule r");
            sql.append(" where EXISTS(select 1 from message_reply_rule_keyword k where ((k.all_match='YES' and k.keyword=:keyword) or (k.all_match='NO' and k.keyword like :keyword2)) and r.id=k.message_reply_rule_id)");
            sql.append(" and r.mall_id=:mallId");
            params.put("mallId",mallId);
            params.put("keyword",keyword);
            params.put("keyword2", "%" + keyword + "%");
            sql.append(" order by r.id desc");
            fields.append("r.*");
        };
        return doing.go(MessageReplyRule.class, objectMapper, jdbcTemplate, log);
    }
}
